package com.persondemo.videoappliction;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.persondemo.videoappliction.component.ApplicationComponent;
import com.persondemo.videoappliction.event.MainEvent;
import com.persondemo.videoappliction.runtimepermissions.PermissionsManager;
import com.persondemo.videoappliction.runtimepermissions.PermissionsResultAction;
import com.persondemo.videoappliction.ui.base.AppManager;
import com.persondemo.videoappliction.ui.base.BaseActivity;
import com.persondemo.videoappliction.ui.base.SupportFragment;
import com.persondemo.videoappliction.ui.dianping.DianPingFragment;
import com.persondemo.videoappliction.ui.duanzi.DuanziFragment;
import com.persondemo.videoappliction.ui.search.SearchFragment;
import com.persondemo.videoappliction.ui.video.MainFragment;
import com.persondemo.videoappliction.ui.vip.MeFragment;
import com.persondemo.videoappliction.utils.StatusBarUtil;
import com.persondemo.videoappliction.utils.T;
import com.persondemo.videoappliction.widget.BottomBar;
import com.persondemo.videoappliction.widget.BottomBarTab;
import com.umeng.analytics.MobclickAgent;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import butterknife.BindView;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;

import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;


public class MainActivity extends BaseActivity {
    @BindView(R.id.bottomBar)
    BottomBar bottomBar;
    @BindView(R.id.contentContainer)
    FrameLayout contentContainer;
    @BindView(R.id.activity_main)
    RelativeLayout activityMain;
    SupportFragment[] mFragments = new SupportFragment[5];
//    @BindView(R.id.fab)
//    FloatingActionButton fab;
    @Override
    public void onRetry() {
    }

    @Override//滑动返回
    public boolean isSupportSwipeBack() {
        return false;
    }

    @Override
    public int getContentLayout() {
        return R.layout.module_activity_main;
    }

    @Override
    public void initInjector(ApplicationComponent appComponent) {

    }

    @Override
    protected void onPause() {
        super.onPause();
        JCVideoPlayer.releaseAllVideos();
    }

    @Override
    public void onBackPressed() {
        if (JCVideoPlayer.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    public void bindView(View view, Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        // fragment 头部是 ImageView 的设置状态栏透明
        StatusBarUtil.hideFakeStatusBarView(MainActivity.this);
        if (savedInstanceState == null) {
            mFragments[0] = MainFragment.newInstance();
            mFragments[1] = SearchFragment.newInstance();
            mFragments[2] = DuanziFragment.newInstance();
            mFragments[3] = DianPingFragment.newInstance();
            mFragments[4] = MeFragment.newInstance();

            getSupportDelegate().loadMultipleRootFragment(R.id.contentContainer, 0,
                    mFragments[0],
                    mFragments[1],
                    mFragments[2],
                    mFragments[3],
                    mFragments[4]);
        } else {
            mFragments[0] = findFragment(MainFragment.class);
            mFragments[3] = findFragment(SearchFragment.class);
            mFragments[1] = findFragment(DuanziFragment.class);
            mFragments[2] = findFragment(DianPingFragment.class);

            mFragments[4] = findFragment(MeFragment.class);
        }
        bottomBar.addItem(new BottomBarTab(this, R.drawable.ic_movie02, "影视"))
                .addItem(new BottomBarTab(this, R.drawable.ic_search, "热搜"))
                .addItem(new BottomBarTab(this, R.drawable.ic_duanzi, "段子"))
                .addItem(new BottomBarTab(this, R.drawable.ic_anime, "点评"))
                .addItem(new BottomBarTab(this, R.drawable.ic_me, "我的"));

        bottomBar.setOnTabSelectedListener(new BottomBar.OnTabSelectedListener() {
            @Override
            public void onTabSelected(int position, int prePosition) {
                getSupportDelegate().showHideFragment(mFragments[position], mFragments[prePosition]);
            }

            @Override
            public void onTabUnselected(int position) {

            }

            @Override
            public void onTabReselected(int position) {

            }
        });
    }

    private void check() {
        PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult(MainActivity.this, new String[]{
                Manifest.permission.READ_PHONE_STATE, WRITE_EXTERNAL_STORAGE
        }, new PermissionsResultAction() {
            @Override
            public void onGranted() {
//                imei = RxDeviceTool.getIMEI(getActivity());
//                if (!TextUtils.isEmpty(imei)){
//                    PreferenceUtil.put("imei",imei);
//                }
            }

            @Override
            public void onDenied(String permission) {
                T.showShort(MainActivity.this, "您已拒绝授权！会导致某些功能无法使用！请开启授权");
//                simpleSetting(MainActivity.this);
            }
        });
    }

    public static void simpleSetting(Context context) {
        Intent intent = new Intent();
        try {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            // 将用户引导到系统设置页面
            if (Build.VERSION.SDK_INT >= 9) {
                Log.e("HLQ_Struggle", "APPLICATION_DETAILS_SETTINGS");
                intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                intent.setData(Uri.fromParts("package", context.getPackageName(), null));
            } else if (Build.VERSION.SDK_INT <= 8) {
                intent.setAction(Intent.ACTION_VIEW);
                intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
                intent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
            }
            context.startActivity(intent);
        } catch (Exception e) {//抛出异常就直接打开设置页面
            Log.e("HLQ_Struggle", e.getLocalizedMessage());
            intent = new Intent(Settings.ACTION_SETTINGS);
            context.startActivity(intent);
        }
    }

    @Override
    public void initData() {
//        check();
    }

    @Override
    public void onBackPressedSupport() {
        super.onBackPressedSupport();
    }
    @Subscriber
    private void gomovie(MainEvent event) {
        if (event == null) return;
        String title = event.title;
        switch (title) {
            case "最新电影":
                bottomBar.setCurrentItem(1);
                break;
            case "电视剧":
                bottomBar.setCurrentItem(2);
                break;
            case "热映动漫":
                bottomBar.setCurrentItem(3);
                break;
            case "会员中心":
                bottomBar.setCurrentItem(4);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private long exitTime = 0;

    //退出app
    private void exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(getApplicationContext(), "再按一次退出程序",
                    Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            MobclickAgent.onKillProcess(MainActivity.this);
            AppManager.getAppManager().finishAllActivity();
            System.exit(0);
        }
    }

}
